import request from '../../utils/request';
import API from '../../config/API';

let isSend = false;     // 搜索框请求优化，函数节流标识

Page({
    data: {
        placeholderContent: '',     // 默认搜索关键字
        hotList: [],                // 热搜榜数据
        keywords: '',               // 搜索关键词
        searchList: [],             // 搜索结果
        historyList: [],            // 搜索历史记录
    },
    // 获取初始化数据
    async getInitData() {
        let result = await Promise.all([
            request(API.searchDefault),
            request(API.searchHotDetail)
        ]);
        this.setData({ 
            placeholderContent: result[0].code === 200 && result[0].data.showKeyword,
            hotList: result[1].code === 200 && result[1].data
        });
    },
    // 搜索框内容改变回调
    handleInputChange(e) {
        let keywords = e.detail.value.trim();
        this.setData({ keywords });
        if (!keywords) {
            this.setData({ searchList: [] });
            return;
        }
        if (isSend) return;
        isSend = true;
        this.getSearchList();
        setTimeout(() => isSend = false, 300);
    },
    // 获取搜索结果
    async getSearchList() {
        let { keywords, historyList } = this.data;
        if (!keywords) return;
        let resp = await request(API.search, { keywords, limit: 10 });
        resp.code === 200 && this.setData({ searchList: resp.result.songs });
        // 将搜索的关键词添加到搜索历史记录中
        let index = historyList.indexOf(keywords);
        if (index !== -1) {
            historyList.splice(index, 1);
        }
        historyList.unshift(keywords);
        this.setData({ historyList });
        wx.setStorageSync('searchHistory', historyList);
    },
    // 清空搜索内容
    clearSearchInput() {
        this.setData({ keywords: '', searchList: [] });
    },
    // 清空搜索历史记录
    deleteSearchHistory() {
        wx.showModal({
            content: '确认删除吗？',
            success: ({ confirm }) => {
                if (confirm) {
                    this.setData({ historyList: [] });
                    wx.removeStorageSync('searchHistory');
                }
            }
        });
    },
    // 生命周期函数--监听页面加载
    onLoad: function (options) {
        this.getInitData();
        // 获取本地历史记录
        let historyList = wx.getStorageSync('searchHistory');
        historyList && this.setData({ historyList });
    }
});